import os
import subprocess

from pyx_package.script import BaseBehavior
from pyx_package.ps_paramete import PsParameter
PYX_MODULE_NAME = "shell(/dos)"

class ScriptBehavior(BaseBehavior):

    def __init__(self) -> None:
        super().__init__()
        
        self.SetExeMode("function")

        self.InitInputParams()

    def InitInputParams(self):
        
        #被执行的命令文本
        self.i_cmd_str = self.CreateParam("cmd str", "命令文本", PsParameter.Input, str, "")
        self.i_cmd_str.keep_value = False

        #是否阻塞
        self.i_wait = self.CreateParam("wait", "等待结束", PsParameter.Input, bool, True)
        self.i_wait.must = False

        #执行所在路径
        self.i_run_dir = self.CreateParam("run dir", "执行所在路径", PsParameter.Input, str, "")
        self.i_run_dir.value = ""
        self.i_run_dir.must = False

        #是否展示打开终端窗口
        self.i_open_dos_window = self.CreateParam("open dos window", "打开dos窗口", PsParameter.Input, bool, True)
        self.i_open_dos_window.must = False

        #是否以shell方式启动
        self.i_shell = self.CreateParam("shell", "是否以shell方式运行", PsParameter.Input, bool, True)
        self.i_shell.must = False

    def DoStep(self):
    
        if os.path.exists(self.i_run_dir.value):

            popen = subprocess.Popen(
                self.i_cmd_str.value,
                cwd=self.i_run_dir.value,
                shell=self.i_shell.value
            )

        else:
            popen = subprocess.Popen(
                self.i_cmd_str.value,
                shell=self.i_shell.value
            )

        #判断是否等待
        if self.i_wait.value:
            popen.wait()